var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');
var cheerio = require('cheerio');

require('superagent-proxy')(superagent);

// cloudmusic
var mysqlConfig1 = require('./config').mysqlConfig1;
// ip
var mysqlConfig2 = require('./config').mysqlConfig2;

var ipList = [];
var ipIndex = 0;
var proxy = '';

function changeIp() {
    if (ipIndex < ipList.length - 1) {
        ipIndex += 1;
    } else {
        ipIndex = 0;
    }
    setProxy();
}

function setProxy() {
    var item = ipList[ipIndex];
    console.log(item);

    var ip = item.ip;
    var port = item.port;

    proxy = `http://${ip}:${port}`;
    console.log('proxy');

    console.log(proxy);

}
function getIpList() {
    var connection1 = mysql.createConnection(mysqlConfig2);
    var query1 = 'select * from ip_table1 where (success_count>=5 and error_count/success_count<2 )';
    connection1.connect();
    connection1.query(query1, function (err, res) {
        if (err) {
            // console.log('query1 error');
            // setTimeout(() => {
            //     getIpList();
            // }, 3000);
        } else {
            ipList = res;
            if (ipList.length > 0) {
                console.log('ip count');
                console.log(ipList.length);

                setProxy();
                setInterval(() => {
                    changeIp();
                }, 300 * 1000);
                start();
            } else {
                console.log('no ip');

            }
        }
    });
    connection1.end();
}
getIpList();
function start() {
    // getSongList(1, 0);
    for (var i = 0; i < 20; i++) {
        var offset = 10 * i
        getSongList(1, offset);
    }
}

function getSongList(limit, offset) {
    var connection2 = mysql.createConnection(mysqlConfig1);
    connection2.connect();

    var query2 = `select * from song where ISNULL(comment_count) LIMIT ${limit} offset ${offset};`
    connection2.query(query2, function (err2, res2) {
        console.log(query2);

        if (err2) {
            console.log('query2 error');
            console.log(err2);


        } else {
            console.log('query2 success');
            console.log(res2);
            if (res2.length > 0) {
                var song = res2[0];
                var songId = song.id;
                getCommentCount(songId);
                function getCommentCount(songId) {
                    console.log('get comment count');

                    let url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_' + songId;
                    superagent.get(url)
                        .timeout(3000)
                        .proxy(proxy)
                        .end(function (err3, res3) {

                            console.log('http end');
                            console.log(proxy);
                            console.log(url);

                            if (err3) {
                                console.log(err3);
                                changeIp();
                                setTimeout(() => {
                                    getSongList(limit, offset);
                                }, 3000);
                            } else {
                                console.log('http success');
                                // console.log(res3.text);
                                let o = {};
                                try {
                                    o = JSON.parse(res3.text);
                                } catch (error) {
                                    getSongList(limit, offset);
                                }
                                // let o = JSON.parse(res3.text);
                                console.log('o');

                                // console.log(o);

                                let commentCount = o.total;

                                // let item = [`${songId}`, commentCount];
                                // console.log(o);

                                // console.log(item);
                                console.log('msg');

                                console.log(o.msg);

                                if (o.msg === '资源不存在') {
                                    commentCount = -1;

                                }
                                console.log(typeof commentCount);

                                if (typeof commentCount === 'number') {
                                    // console.log(item);
                                    upload();
                                    function upload() {
                                        console.log('do upload');

                                        var connection4 = mysql.createConnection(mysqlConfig1);
                                        connection4.connect();

                                        var query4 = `update song set comment_count=${commentCount} where id=${songId}`;
                                        console.log(query4);

                                        connection4.query(query4, function (err4, res4) {
                                            if (err4) {
                                                console.log('query4 err');

                                                console.log(err4);

                                            } else {
                                                console.log('query4 success');
                                                console.log(res4);
                                                getSongList(limit, offset);
                                                // connection4.destroy();
                                                // connection4.
                                            }
                                        });
                                        connection4.end();
                                    }
                                } else {
                                    if (o.msg === 'Cheating') {
                                        console.log('cheating');
                                        setTimeout(() => {
                                            changeIp();
                                            getSongList(limit, offset);
                                        }, 3000);
                                    } else {
                                        getSongList(limit, offset + 1);
                                    }
                                }
                            }
                        })
                }
            } else {
                console.log('no song');

            }
        }
    });
    connection2.end();
}
